package com.sxau.software_educational_system_backend.controller;

import com.alibaba.fastjson.JSON;
import com.sxau.software_educational_system_backend.common.BaseResponse;
import com.sxau.software_educational_system_backend.common.ErrorCode;
import com.sxau.software_educational_system_backend.common.ResultUtils;
import com.sxau.software_educational_system_backend.constant.JwtClaimsConstant;
import com.sxau.software_educational_system_backend.context.BaseContext;
import com.sxau.software_educational_system_backend.domain.entity.Admin;
import com.sxau.software_educational_system_backend.domain.properties.JwtProperties;
import com.sxau.software_educational_system_backend.domain.req.ReqLoginDTO;
import com.sxau.software_educational_system_backend.domain.resp.UserVO;
import com.sxau.software_educational_system_backend.service.AdminService;
import com.sxau.software_educational_system_backend.utils.JwtUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@ApiOperation("用户信息管理接口")
public class UserController {

    private final AdminService adminService;

    private final JwtProperties jwtProperties;

    @ApiOperation("登录")
    @PostMapping("/login")
    public BaseResponse<UserVO> login(@RequestBody @Validated ReqLoginDTO reqLoginDTO) throws AccountLockedException, AccountNotFoundException {

        Admin admin = adminService.login(reqLoginDTO);

        UserVO userVO = new UserVO();

        if (admin == null) {
            return ResultUtils.error(ErrorCode.NOT_EXIT);
        } else {
            BaseContext.setCurrentUser(admin);
        }
        String modelJson = JSON.toJSONString(admin);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN, modelJson);
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        userVO.setToken(token);
        userVO.setRole(admin.getRole());

        return ResultUtils.success(userVO);
    }

}
